package com.sunseagear.wind.modules.test.table.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.test.table.entity.Table;
import com.sunseagear.wind.modules.test.table.entity.query.TableQuery;
import com.sunseagear.wind.modules.test.table.service.ITableService;
import com.sunseagear.wind.common.utils.excel.ExcelUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @version V1.0
 * @package com.sunseagear.wind.modules.sys.controller
 * @title: 操作日志控制器
 * @description: 操作日志控制器 * @date: 2018-09-30 15:53:25
 * @copyright: 2018 www.sunseagear.com Inc. All rights reserved.
 */

@RestController
@RequestMapping("test/table/table")
@Log(title = "综合表格")
@RequiredArgsConstructor
public class TableController extends BaseBeanController {

    private final ITableService tableService;

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     */
    @GetMapping(value = "list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("test:table:table:list")
    public RPage<Table> list(TableQuery query) {
        //加入条件
        QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date")
                .eq(ObjectUtil.isNotEmpty(query.getTitle()), "title", query.getTitle())
                .eq(ObjectUtil.isNotEmpty(query.getLevel()), "level", query.getLevel())
                .eq(ObjectUtil.isNotEmpty(query.getType()), "type", query.getType());
        // 预处理
        Page<Table> pageBean = tableService.page(getPage(), queryWrapper);
        return RPage.success(pageBean);
    }

    @PostMapping("add")
    @Log(logType = LogType.INSERT)
    @SaCheckPermission("test:table:table:add")
    public R<Void> add(@Validated @RequestBody Table entity) {
        tableService.save(entity);
        return R.success("添加成功");
    }

    @PutMapping("update")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("test:table:table:update")
    public R<Void> update(@Validated @RequestBody Table entity) {
        tableService.saveOrUpdate(entity);
        return R.success("更新成功");
    }

    @GetMapping("detail/{id}")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("test:table:table:detail")
    public R<Table> detail(@PathVariable("id") Long id) {
        Table tableEntity = tableService.getById(id);
        return R.success(tableEntity);
    }

    @DeleteMapping("delete")
    @Log(logType = LogType.DELETE)
    @SaCheckPermission("test:table:table:delete")
    public R<Void> delete(@RequestParam("ids") List<Long> idList) {
        tableService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

    @GetMapping("template")
    @Log(logType = LogType.IMPORT)
    @SaCheckPermission("test:table:table:import")
    public R<HashMap<String, Object>> template() {
        try {
            HashMap<String, Object> result = ExcelUtils.template("综合表格", Table.class);
            return R.success(result);
        } catch (Exception e) {
            log.error("Template Exception", e);
            return R.fail("导出模板失败！失败信息：" + e.getMessage());
        }
    }

    @PostMapping("import")
    @Log(logType = LogType.IMPORT)
    @SaCheckPermission("test:table:table:import")
    public R<Void> importData(MultipartFile file) {
        try {
            List<Table> list = ExcelUtils.importData(file, Table.class, 1, 0);
            tableService.saveBatch(list);
            return R.success("导入成功");
        } catch (Exception e) {
            log.error("Import Exception", e);
            return R.fail("导出模板失败！失败信息：" + e.getMessage());
        }
    }

    @PostMapping("export")
    @Log(logType = LogType.EXPORT)
    @SaCheckPermission("test:table:table:export")
    public R<Map<String, Object>> export(TableQuery query) {
        try {
            QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date")
                    .eq(ObjectUtil.isNotEmpty(query.getTitle()), "title", query.getTitle())
                    .eq(ObjectUtil.isNotEmpty(query.getLevel()), "level", query.getLevel())
                    .eq(ObjectUtil.isNotEmpty(query.getType()), "type", query.getType());
            List<Table> list = tableService.list(queryWrapper);

            HashMap<String, Object> result = ExcelUtils.export(list, "综合表格", Table.class);
            return R.success(result);
        } catch (Exception e) {
            log.error("Export Exception", e);
            return R.fail("导出记录失败！失败信息：" + e.getMessage());
        }

    }
}
